<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%><%@ page import="java.io.InputStream"
%><%@ page import="java.io.OutputStream"
%><%@ page import="java.io.FileInputStream"
%><%@ page import="java.io.File"
%><%@ page import="java.io.IOException"
%><%@ page import="java.util.Calendar"%><%

try {
    this.download(request, response);
} catch (IOException e) {
    e.printStackTrace();
    out.write("<script type=\"text/javascript\">window.alert(\"文件下载出错，无法下载！\");</script>");
}

%><%!
@SuppressWarnings("deprecation")
private void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    String realPath = request.getRealPath("");
    String path = request.getParameter("path");
    if (null == path) {
        path = "";
    }
    String filePath = realPath + path.trim();
    
    InputStream is = null;
    OutputStream os = null;

    try {
        File f = new File(filePath);
        if (f.exists() && f.isFile()) {
            String fileName = f.getName();
            int index = fileName.lastIndexOf('.');
            String suffix = (-1 == index || fileName.length() == (index + 1)) ? "" : fileName.substring(index);
            
            response.setHeader("Content-Disposition",
                    String.format("attachment;filename=\"%1$s\"",
                            String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS%1$tL", Calendar.getInstance()) + suffix));
            
            is = new FileInputStream(f);
            os = response.getOutputStream();
            this.is2os(is, os);
        } else {
            throw new IOException(String.format("文件不存在\n[%1$s]\n[%2$s]", path, f.getAbsolutePath()));
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        this.close(is);
        this.close(os);
    }
}

private void is2os(InputStream is, OutputStream os) throws IOException {
    int length = -1;
    byte[] bs = new byte[1024 * 8];
    while (0 < (length = is.read(bs))) {
        os.write(bs, 0, length);
    }
    os.flush();
}

private void close(InputStream... iss) {
    if (null != iss && 0 < iss.length) {
        for (InputStream is : iss) {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

private void close(OutputStream... oss) {
    if (null != oss && 0 < oss.length) {
        for (OutputStream os : oss) {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
%>